<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\task\Task as Model;
use app\models\task\TaskImage;
use app\models\task\TaskList;
use app\models\user\User;
use app\models\user\UserLevel;
use app\services\Upload as Service;
use app\util\Util;

class TaskController extends H5Controller
{
    /**
     * news list
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionList()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->where(['status' => Model::$statusMapping['OK']]);
            // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['image'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    /**
     * news view
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionView()
    {
        $id = $this->post('id');

        $model = Model::find()
            ->where(['id' => $id])
            ->andWhere(['status' => Model::$statusMapping['OK']])
            // ->with(['image'])
            ->asArray()
            ->one();
        if ($model) {
            // convert images
            $convert = Util::convertImages($model['content']);
            $model['inImages'] = $convert['images'];
            $model['inText'] = $convert['text'];

            unset($model['content']);

            return $this->successEncode($model);
        }

        return $this->nothing();
    }

    // 判断是否接收过
    public function actionCheck()
    {
        $id = $this->post('id');

        $has = TaskList::find()
            ->where(['task_id' => $id])
            ->andWhere(['user_id' => $this->user->id])
            // 判断今天的
            ->andWhere(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->one();

        if ($has) {
            $check = $has->status != TaskList::$statusMapping['REJECT'];
        } else {
            $check = false;
        }

        return $this->successEncode(['check' => $check]);
    }

    public function actionSave()
    {
        $id = $this->post('id');

        $model = Model::findOne(['id' => $id]);
        if (!$model) {
            return $this->fail();
        }

        // 判断 等级
        $user = User::findOne(['id' => $this->user->id]);
        if ($user->level < UserLevel::$keys['vip1']) {
            return $this->fail('您等级不够,不能领取');
        }

        // 判断是否为今天的
        $time = date('Y-m-d', strtotime($model->create_time));
        $time = strtotime($time);
        $now = strtotime(date('Y-m-d'));
        if ($time != $now) {
            // return $this->fail('已过期');
        }

        // 判断是否已经接收过
        $has = TaskList::find()
            ->where(['task_id' => $id])
            ->andWhere(['user_id' => $this->user->id])
            // 判断今天的
            ->andWhere(['DATE_FORMAT(create_time, "%Y-%m-%d")' => date('Y-m-d')])
            ->one();
        if ($has && $has->status != TaskList::$statusMapping['REJECT']) {
            return $this->fail('您已经接收过了,请勿重复操作');
        }

        $ops = new TaskList();
        $ops->user_id = $this->user->id;
        $ops->task_id = $id;
        $ops->status = 1;
        $ops->save();

        $model->num += 1;
        $model->save();

        return $this->success();
    }

    // 全部已接收任务
    public function actionGetOrderList()
    {
        $s = intval($this->post('status'));

        switch ($s) {
            case 1:
                $status = TaskList::$statusMapping['WAIT'];
                break;
            case 2:
                $status = TaskList::$statusMapping['CHECK'];
                break;
            case 3:
                $status = TaskList::$statusMapping['FINISH'];
                break;
            case 4:
                $status = TaskList::$statusMapping['REJECT'];
                break;
            default:
                $status = TaskList::$statusMapping['ALL'];
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = TaskList::find()
            ->andWhere(['user_id' => $this->user->id]);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['task.image'])
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 上传凭证
    public function actionUpload()
    {
        $result = Service::uploadImage('task');

        if ($result) {

            $id = $this->post('id');
            $task = TaskList::findOne(['id' => $id, 'user_id' => $this->user->id]);
            if (!$task) {
                return $this->fail('操作失败');
            }
            if ($task->status != TaskList::$statusMapping['WAIT']) {
                // return $this->fail('不需要再上传凭证');
            }

            $image_id = $result['id'];

            // 写入到图片库
            $model = new TaskImage();
            $model->task_id = $task->task_id;
            $model->task_list_id = $task->id;
            $model->image_id = $image_id;
            if ($model->save()) {
                $result['id'] = $model->id;
                return $this->success($result, '上传成功');
            }
        } else {
            return $this->fail('上失败,' . Service::getLastError());
        }
    }

    // 上传的图片列表
    public function actionGetUploadList()
    {
        $id = $this->post('id');
        $list = TaskImage::find()
            ->where(['task_list_id' => $id])
            ->with(['image'])
            ->asArray()
            ->all();

        if (!$list) {
            return $this->successEncode([
                'list' => []
            ]);
        }

        // var_dump($list);exit;

        $urls = [];
        foreach ($list as $item) {
            if ($item['image'] && $item['image']['path']) {
                array_push($urls, [
                    'path' => $item['image']['path'],
                    'id' => $item['id'],
                ]);
            }
        }

        // var_dump($urls);exit;

        $task = TaskList::findOne(['id' => $id]);

        return $this->successEncode([
            'list' => $urls,
            'check' => $task->status === TaskList::$statusMapping['CHECK']
        ]);
    }

    public function actionRemoveUpload()
    {
        $id = $this->post('id');

        // todo 如果删除完了, 是否要处理状态

        $model = TaskImage::findOne(['id' => $id]);
        if ($model) {
            // var_dump($model);exit;
            $task = TaskList::findOne(['id' => $model->task_list_id]);
            if ($task->status == TaskList::$statusMapping['FINISH']) {
                return $this->fail('已完成,不能删除!');
            }
            if ($model->delete()) {
                return $this->success();
            }
        }

        return $this->fail('操作失败');
    }

    // 审核上传
    public function actionCheckUpload()
    {
        $id = $this->post('id');

        $task = TaskList::findOne(['id' => $id]);

        if ($task) {
            $task->status = TaskList::$statusMapping['CHECK'];
            $task->save();

            return $this->success();
        }
    }
}